package com.example.crossborderecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crossborderecommerce.entity.*;
import com.example.crossborderecommerce.entity.Currency;
import com.example.crossborderecommerce.mapper.CustomerOrderMapper;
import com.example.crossborderecommerce.service.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 客户订单模块
 *
 * @author Yolanda
 * @since 2024-05-09
 */
@RestController
@Transactional
@RequestMapping("/customer-order")
public class CustomerOrderController {
    @Resource
    ICustomerOrderService customerOrderService;
    @Resource
    CustomerOrderMapper customerOrderMapper;
    @Resource
    ISalePromotionService salePromotionService;
    @Resource
    ICustomerService customerService;
    @Resource
    IShopService shopService;
    @Resource
    IProductService productService;
    @Resource
    ILogisticsProviderService logisticsProviderService;
    @Resource
    ICurrencyService currencyService;
    @Resource
    IStoreCommodityService storeCommodityService;
    @Resource
    IStoreService storeService;

    /**
     * 添加客户订单
     * @param customerOrder
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody CustomerOrder customerOrder){
        StoreCommodity storeCommodity = storeCommodityService.getById(customerOrder.getStoreCommodityId());
        if (storeCommodity.getQuantity()<customerOrder.getQuantity()){
            return Result.error("库存不足！");
        }
        boolean res = customerOrderService.save(customerOrder);
//        if(res){
//            return Result.success("添加客户订单成功！");
//        }
//        return Result.error("添加客户订单失败！");

        if (res) {
            // 获取保存后的订单ID
            Integer orderId = customerOrder.getId();
            // 返回订单ID和成功消息
            Map<String, Object> data = new HashMap<>();
            data.put("id", orderId);
            return Result.success("添加客户订单成功！", data);
        }
        return Result.error("添加客户订单失败！");
    }

    /**
     * 分页查询所有的客户订单
     * @param customerName
     * @param status
     * @param logisticsProviderId
     * @param salePromotionId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(@RequestParam(defaultValue = "") String customerName,
                           @RequestParam(defaultValue = "") String status,
                           @RequestParam(defaultValue = "-1") String logisticsProviderId,
                           @RequestParam(defaultValue = "-1") String salePromotionId,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        Page<CustomerOrder> customerOrderPage = new Page<>(pageNum, pageSize);
        List<CustomerOrder> customerOrderList = customerOrderMapper.getCustomerOrderByPage(customerOrderPage, customerName, status, logisticsProviderId,salePromotionId);
        for(CustomerOrder customerOrder : customerOrderList) {
            if(customerOrder.getLogisticsProviderId() != null) {
                LogisticsProvider logisticsProvider = logisticsProviderService.getById(customerOrder.getLogisticsProviderId());
                customerOrder.setLogisticsProviderName(logisticsProvider.getName());
            }
            if(customerOrder.getStoreCommodityId() != null) {
                StoreCommodity storeCommodity = storeCommodityService.getById(customerOrder.getStoreCommodityId());
                Product product = productService.getById(storeCommodity.getProductId());
                customerOrder.setProductId(storeCommodity.getProductId());
                customerOrder.setProductName(product.getName());
                customerOrder.setStoreId(storeCommodity.getStoreId());
                Store store = storeService.getById(storeCommodity.getStoreId());
                customerOrder.setStoreName(store.getName());
            }
            if(customerOrder.getShopId() != null) {
                Shop shop = shopService.getById(customerOrder.getShopId());
                if(shop != null) {
                    customerOrder.setShopName(shop.getName());
                }
            }
            if(customerOrder.getCustomerId() != null) {
                Customer customer = customerService.getById(customerOrder.getCustomerId());
                customerOrder.setCustomerName(customer.getName());
                customerOrder.setCustomerNation(customer.getNation());
            }
            if(customerOrder.getSalePromotionId() != null) {
                SalePromotion salePromotion = salePromotionService.getById(customerOrder.getSalePromotionId());
                customerOrder.setSalePromotionName(salePromotion.getName());
            }
            if(customerOrder.getCurrencyId() != null) {
                Currency currency = currencyService.getById(customerOrder.getCurrencyId());
                customerOrder.setCurrency(currency.getNameBefore());
            }
        }
        Page<CustomerOrder> newCustomerOrderPage = new Page<>(pageNum, pageSize);
        newCustomerOrderPage.setRecords(customerOrderList);
        newCustomerOrderPage.setTotal(customerOrderPage.getTotal());
        return Result.success("成功查询所有客户订单！",newCustomerOrderPage);
    }

    /**
     * 删除客户订单
     * @param customerOrder
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody CustomerOrder customerOrder) {
        boolean res = customerOrderService.removeById(customerOrder);
        if(res) {
            return Result.success("删除客户订单成功！");
        }
        return Result.error("删除客户订单失败！");
    }

    /**
     * 删除一系列客户订单
     * @param ids
     * @return
     */
    @GetMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam String ids) {
        List<String> customerOrderIds = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        boolean res = customerOrderService.removeByIds(customerOrderIds);
        if(res) {
            return Result.success("删除客户订单成功！");
        }
        return Result.error("删除客户订单失败！");
    }

    /**
     * 获取全部客户订单
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll(){
        List<CustomerOrder> customerOrderList = customerOrderService.list();
        if (customerOrderList == null){
            return Result.error("获取全部客户订单失败！");
        }
        for(CustomerOrder customerOrder : customerOrderList){
            if(customerOrder.getLogisticsProviderId() != null) {
                LogisticsProvider logisticsProvider = logisticsProviderService.getById(customerOrder.getLogisticsProviderId());
                customerOrder.setLogisticsProviderName(logisticsProvider.getName());
            }
            if(customerOrder.getStoreCommodityId() != null) {
                StoreCommodity storeCommodity = storeCommodityService.getById(customerOrder.getStoreCommodityId());
                Product product = productService.getById(storeCommodity.getProductId());
                customerOrder.setProductId(storeCommodity.getProductId());
                customerOrder.setProductName(product.getName());
                customerOrder.setStoreId(storeCommodity.getStoreId());
                Store store = storeService.getById(storeCommodity.getStoreId());
                customerOrder.setStoreName(store.getName());
            }
            if(customerOrder.getShopId() != null) {
                Shop shop = shopService.getById(customerOrder.getShopId());
                customerOrder.setShopName(shop.getName());
            }
            if(customerOrder.getCustomerId() != null) {
                Customer customer = customerService.getById(customerOrder.getCustomerId());
                customerOrder.setCustomerName(customer.getName());
            }
            if(customerOrder.getSalePromotionId() != null) {
                SalePromotion salePromotion = salePromotionService.getById(customerOrder.getSalePromotionId());
                customerOrder.setSalePromotionName(salePromotion.getName());
            }
            if(customerOrder.getCurrencyId() != null) {
                Currency currency = currencyService.getById(customerOrder.getCurrencyId());
                customerOrder.setCurrency(currency.getNameBefore());
            }
        }
        return Result.success("获取全部产品属性成功",customerOrderList);
    }

    /**
     * 修改客户订单
     * @param customerOrder
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody CustomerOrder customerOrder) {
        // 设置更新时间为当前时间
        customerOrder.setUpdateTime(LocalDateTime.now());
        boolean res = customerOrderService.saveOrUpdate(customerOrder);
        if (res) {
            return Result.success("修改客户订单成功！");
        }
        return Result.error("修改客户订单失败！");
    }

    /**
     * 修改客户订单状态
     * @param customerOrderId
     * @param status
     * @return
     */
    @GetMapping ("/updateStatus")
    public Result updateStatus(@RequestParam String customerOrderId,@RequestParam String status) {
        CustomerOrder customerOrder = customerOrderService.getById(customerOrderId);
        // 设置更新时间为当前时间
        customerOrder.setUpdateTime(LocalDateTime.now());
        customerOrder.setStatus(status);
        boolean res = customerOrderService.saveOrUpdate(customerOrder);
        if (res) {
            return Result.success("修改客户订单成功！");
        }
        return Result.error("修改客户订单失败！");
    }

    /**
     * 导出客户订单
     * @param customerName
     * @param status
     * @param logisticsProviderId
     * @param salePromotionId
     * @return
     */
    @GetMapping("exportCustomerOrderList")
    public Result exportCustomerOrderList(@RequestParam(defaultValue = "") String customerName,
                                         @RequestParam(defaultValue = "") String status,
                                         @RequestParam(defaultValue = "-1") String logisticsProviderId,
                                         @RequestParam(defaultValue = "-1") String salePromotionId,
                                         HttpServletResponse response) {
        QueryWrapper<CustomerOrder> queryWrapper = new QueryWrapper<>();
        List<CustomerOrder> customerOrderList = customerOrderService.list(queryWrapper);
        for(CustomerOrder customerOrder : customerOrderList) {
            if(customerOrder.getLogisticsProviderId() != null) {
                LogisticsProvider logisticsProvider = logisticsProviderService.getById(customerOrder.getLogisticsProviderId());
                customerOrder.setLogisticsProviderName(logisticsProvider.getName());
            }
            if(customerOrder.getStoreCommodityId() != null) {
                StoreCommodity storeCommodity = storeCommodityService.getById(customerOrder.getStoreCommodityId());
                Product product = productService.getById(storeCommodity.getProductId());
                customerOrder.setProductId(storeCommodity.getProductId());
                customerOrder.setProductName(product.getName());
                customerOrder.setStoreId(storeCommodity.getStoreId());
                Store store = storeService.getById(storeCommodity.getStoreId());
                customerOrder.setStoreName(store.getName());
            }
            if(customerOrder.getShopId() != null) {
                Shop shop = shopService.getById(customerOrder.getShopId());
                if(shop != null) {
                    customerOrder.setShopName(shop.getName());
                }
            }
            if(customerOrder.getCustomerId() != null) {
                Customer customer = customerService.getById(customerOrder.getCustomerId());
                customerOrder.setCustomerName(customer.getName());
                customerOrder.setCustomerNation(customer.getNation());
            }
            if(customerOrder.getSalePromotionId() != null) {
                SalePromotion salePromotion = salePromotionService.getById(customerOrder.getSalePromotionId());
                customerOrder.setSalePromotionName(salePromotion.getName());
            }
            if(customerOrder.getCurrencyId() != null) {
                Currency currency = currencyService.getById(customerOrder.getCurrencyId());
                customerOrder.setCurrency(currency.getNameBefore());
            }
        }
        HSSFWorkbook wb = new HSSFWorkbook(); // 导出到excel文件中
        HSSFSheet sheet = wb.createSheet("表一");
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("ID");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("订单状态");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("产品");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("数量");
        cell.setCellStyle(style);
        cell = row.createCell((short)4);
        cell.setCellValue("金额");
        cell.setCellStyle(style);
        cell = row.createCell((short)5);
        cell.setCellValue("币种");
        cell.setCellStyle(style);
        cell = row.createCell((short)6);
        cell.setCellValue("店铺");
        cell.setCellStyle(style);
        cell = row.createCell((short)7);
        cell.setCellValue("物流商");
        cell.setCellStyle(style);
        cell = row.createCell((short)8);
        cell.setCellValue("客户名称");
        cell.setCellStyle(style);
        cell = row.createCell((short)9);
        cell.setCellValue("客户电话");
        cell.setCellStyle(style);
        cell = row.createCell((short)10);
        cell.setCellValue("国家");
        cell.setCellStyle(style);
        cell = row.createCell((short)11);
        cell.setCellValue("促销活动");
        cell.setCellStyle(style);
        cell = row.createCell((short)12);
        cell.setCellValue("创建时间");
        cell.setCellStyle(style);
        cell = row.createCell((short)13);
        cell.setCellValue("修改时间");
        cell.setCellStyle(style);
        SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < customerOrderList.size(); i++) {
            row = sheet.createRow(i + 1);
            CustomerOrder customerOrder = customerOrderList.get(i);
            row.createCell((short) 0).setCellValue(customerOrder.getId());
            row.createCell((short) 1).setCellValue(customerOrder.getStatus());
            row.createCell((short) 2).setCellValue(customerOrder.getProductName());
            row.createCell((short) 3).setCellValue(customerOrder.getQuantity());
            row.createCell((short) 4).setCellValue(customerOrder.getPrice());
            row.createCell((short) 5).setCellValue(customerOrder.getCurrency());
            row.createCell((short) 6).setCellValue(customerOrder.getShopName());
            row.createCell((short) 7).setCellValue(customerOrder.getLogisticsProviderName());
            row.createCell((short) 8).setCellValue(customerOrder.getCustomerName());
            row.createCell((short) 9).setCellValue(customerOrder.getCustomerPhone());
            row.createCell((short) 10).setCellValue(customerOrder.getSalePromotionName());
            row.createCell((short) 11).setCellValue(customerOrder.getCustomerNation());
            try {
                Date createTime = inputDateFormat.parse(customerOrder.getCreateTime().toString());
                row.createCell((short) 12).setCellValue(outputDateFormat.format(createTime));
            } catch (ParseException e) {
                row.createCell((short) 12).setCellValue(customerOrder.getCreateTime().toString());
            }
            try {
                Date updateTime = inputDateFormat.parse(customerOrder.getUpdateTime().toString());
                row.createCell((short) 13).setCellValue(outputDateFormat.format(updateTime));
            } catch (ParseException e) {
                row.createCell((short) 13).setCellValue(customerOrder.getUpdateTime().toString());
            }
        }
        String fileName = "exportCustomerOrderList.xls";
        // 用户下载
        try {
            ServletOutputStream outputStream = null;
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success("exportProductBrandList");
    }

    /**
     * 获取总的销售量
     * @return
     */
    @GetMapping("/getSaleAmount")
    public Result getSaleAmount() {
        return Result.success(customerOrderMapper.getSaleAmount());
    }

    /**
     * 获取近一周的销售量
     * @return
     */
    @GetMapping("/getSaleAmountInWeek")
    public Result getSaleAmountInWeek() {
        LocalDate today = LocalDate.now();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Integer> saleAmountInWeek = new LinkedList<>();
        // 循环七天
        for (int i = 6; i >= 0; --i) {
            LocalDate currentDay = today.plusDays(-i);
            LocalDateTime startOfDay = LocalDateTime.of(currentDay, LocalTime.MIDNIGHT);
            LocalDateTime endOfDay = LocalDateTime.of(currentDay, LocalTime.of(23, 59, 59));
            Date startDate = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
            Date endDate = Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());

            String formattedStartDate = sdf.format(startDate);
            String formattedEndDate = sdf.format(endDate);

            Integer saleAmount = customerOrderMapper.getSaleAmountDuration(formattedStartDate, formattedEndDate);
            saleAmountInWeek.add(saleAmount);
        }
        return Result.success(saleAmountInWeek);
    }

    /**
     * 获取昨天的销售量
     * @return
     */
    @GetMapping("/getSaleAmountInYesterday")
    public Result getSaleAmountInYesterday() {
        LocalDate today = LocalDate.now();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LocalDate currentDay = today.plusDays(-1);
        LocalDateTime startOfDay = LocalDateTime.of(currentDay, LocalTime.MIDNIGHT);
        LocalDateTime endOfDay = LocalDateTime.of(currentDay, LocalTime.of(23, 59, 59));
        Date startDate = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());

        String formattedStartDate = sdf.format(startDate);
        String formattedEndDate = sdf.format(endDate);

        Integer saleAmount = customerOrderMapper.getSaleAmountDuration(formattedStartDate, formattedEndDate);
        return Result.success(saleAmount);
    }


    /**
     * 获取总的销售额
     * @return
     */
    @GetMapping("/getSaleMoney")
    public Result getSaleMoney() {
        return Result.success(customerOrderMapper.getSaleMoney());
    }

    /**
     * 获取近一周的销售额
     * @return
     */
    @GetMapping("/getSaleMoneyInWeek")
    public Result getSaleMoneyInWeek() {
        LocalDate today = LocalDate.now();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Double> saleMoneyInWeek = new LinkedList<>();
        // 循环七天
        for (int i = 6; i >= 0; --i) {
            LocalDate currentDay = today.plusDays(-i);
            LocalDateTime startOfDay = LocalDateTime.of(currentDay, LocalTime.MIDNIGHT);
            LocalDateTime endOfDay = LocalDateTime.of(currentDay, LocalTime.of(23, 59, 59));

            Date startDate = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
            Date endDate = Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());

            String formattedStartDate = sdf.format(startDate);
            String formattedEndDate = sdf.format(endDate);

            Double saleMoney = customerOrderMapper.getSaleMoneyDuration(formattedStartDate, formattedEndDate);
            saleMoneyInWeek.add(saleMoney);
        }
        return Result.success(saleMoneyInWeek);
    }

    /**
     * 获取昨天的销售额
     * @return
     */
    @GetMapping("/getSaleMoneyInYesterday")
    public Result getSaleMoneyInYesterday() {
        LocalDate today = LocalDate.now();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LocalDate currentDay = today.plusDays(-1);
        LocalDateTime startOfDay = LocalDateTime.of(currentDay, LocalTime.MIDNIGHT);
        LocalDateTime endOfDay = LocalDateTime.of(currentDay, LocalTime.of(23, 59, 59));
        Date startDate = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());

        String formattedStartDate = sdf.format(startDate);
        String formattedEndDate = sdf.format(endDate);

        Double saleMoney = customerOrderMapper.getSaleMoneyDuration(formattedStartDate, formattedEndDate);
        return Result.success(saleMoney);
    }

    /**
     * 获取销售利润
     *
     * @return
     */
    @GetMapping("/getSaleProfit")
    public Result getSaleProfit() {
        QueryWrapper<CustomerOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "已完成");
        List<CustomerOrder> customerOrderList = customerOrderService.list(queryWrapper);
        double totalCost = 0;
        for(CustomerOrder customerOrder : customerOrderList) {
            StoreCommodity storeCommodity = storeCommodityService.getById(customerOrder.getStoreCommodityId());
            Product product = productService.getById(storeCommodity.getProductId());
            customerOrder.setProductId(storeCommodity.getProductId());
            totalCost += product.getCost() * customerOrder.getQuantity();
        }
        double saleMoney = customerOrderMapper.getSaleMoney();
        return Result.success(saleMoney - totalCost);
    }

    /**
     * 获取近一周的毛利润
     * @return
     */
    @GetMapping("/getSaleProfitInWeek")
    public Result getSaleProfitInWeek() {
        LocalDate today = LocalDate.now();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Double> saleAmountInWeek = new LinkedList<>();
        // 循环七天
        for (int i = 6; i >= 0; --i) {
            LocalDate currentDay = today.plusDays(-i);
            LocalDateTime startOfDay = LocalDateTime.of(currentDay, LocalTime.MIDNIGHT);
            LocalDateTime endOfDay = LocalDateTime.of(currentDay, LocalTime.of(23, 59, 59));
            Date startDate = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
            Date endDate = Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
            String formattedStartDate = sdf.format(startDate);
            String formattedEndDate = sdf.format(endDate);

            QueryWrapper<CustomerOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", "已完成");
            queryWrapper.between("create_time", formattedStartDate, formattedEndDate);
            List<CustomerOrder> customerOrderList = customerOrderService.list(queryWrapper);
            double totalCost = 0;
            for(CustomerOrder customerOrder : customerOrderList) {
                StoreCommodity storeCommodity = storeCommodityService.getById(customerOrder.getStoreCommodityId());
                Product product = productService.getById(storeCommodity.getProductId());
                customerOrder.setProductId(storeCommodity.getProductId());
                totalCost += product.getCost() * customerOrder.getQuantity();
            }
            double saleMoney = customerOrderMapper.getSaleMoneyDuration(formattedStartDate, formattedEndDate);
            saleAmountInWeek.add(saleMoney - totalCost);
        }
        return Result.success(saleAmountInWeek);
    }

    /**
     * 获取昨天的毛利润
     * @return
     */
    @GetMapping("/getSaleProfitInYesterday")
    public Result getSaleProfitInYesterday() {
        LocalDate today = LocalDate.now();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LocalDate currentDay = today.plusDays(-1);
        LocalDateTime startOfDay = LocalDateTime.of(currentDay, LocalTime.MIDNIGHT);
        LocalDateTime endOfDay = LocalDateTime.of(currentDay, LocalTime.of(23, 59, 59));
        Date startDate = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
        String formattedStartDate = sdf.format(startDate);
        String formattedEndDate = sdf.format(endDate);

        QueryWrapper<CustomerOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "已完成");
        queryWrapper.between("create_time", formattedStartDate, formattedEndDate);
        List<CustomerOrder> customerOrderList = customerOrderService.list(queryWrapper);
        double totalCost = 0;
        for(CustomerOrder customerOrder : customerOrderList) {
            StoreCommodity storeCommodity = storeCommodityService.getById(customerOrder.getStoreCommodityId());
            Product product = productService.getById(storeCommodity.getProductId());
            customerOrder.setProductId(storeCommodity.getProductId());
            totalCost += product.getCost() * customerOrder.getQuantity();
        }
        double saleMoney = customerOrderMapper.getSaleMoneyDuration(formattedStartDate, formattedEndDate);
        return Result.success(saleMoney - totalCost);
    }

    /**
     * 获取站点的销售利润
     *
     * @return
     */
    @GetMapping("/getSaleProfitByNation")
    public Result getSaleProfitByNation(@RequestParam("nation") String nation) {
        double saleMoney = customerOrderMapper.getSaleMoneyByNation(nation);
        double cost = customerOrderMapper.getProductCostByNation(nation);
        return Result.success(saleMoney - cost);
    }

    /**
     * 获取站点的销售利率
     *
     * @return
     */
    @GetMapping("/getSaleProfitRateByNation")
    public Result getSaleProfitRateByNation(@RequestParam("nation") String nation) {
        double saleMoney = customerOrderMapper.getSaleMoneyByNation(nation);
        double cost = customerOrderMapper.getProductCostByNation(nation);
        return Result.success((saleMoney - cost)/saleMoney);
    }

    /**
     * 根据站点（国家）获取该国家的销售量
     * @param nation
     * @return
     */
    @GetMapping("/getSaleAmountByNation")
    public Result getSaleAmountByNation(@RequestParam("nation") String nation) {
        return Result.success(customerOrderMapper.getSaleAmountByNation(nation));
    }

    /**
     * 根据站点（国家）获取该国家的总销售额
     * @param nation
     * @return
     */
    @GetMapping("/getSaleMoneyByNation")
    public Result getSaleMoneyByNation(@RequestParam("nation") String nation) {
        return Result.success(customerOrderMapper.getSaleMoneyByNation(nation));
    }

    /**
     * 按照产品大类进行销售额统计
     */
    @GetMapping("/getSaleMoneyByCategory")
    public Result getSaleMoneyByCategory() {
        List<Map<String, Double>> list = customerOrderMapper.getSaleMoneyByCategory();
        return Result.success(list);
    }

    /**
     * 按照货物名称进行销售量统计
     */
    @GetMapping("/getSaleAmountByStoreCommodity")
    public Result getSaleAmountByStoreCommodity() {
        List<Map<String, Double>> list = customerOrderMapper.getSaleAmountByStoreCommodity();
        return Result.success(list);
    }

    /**
     * 根据仓库类型获取销售量
     * @param type
     * @return
     */
    @GetMapping("/getSaleAmountByStoreType")
    public Result getSaleAmountByStoreType(@RequestParam("type") String type) {
        return Result.success(customerOrderMapper.getSaleAmountByStoreType(type));
    }
    /**
     * 根据仓库类型获取销售额
     * @param type
     * @return
     */
    @GetMapping("/getSaleMoneyByStoreType")
    public Result getSaleMoneyByStoreType(@RequestParam("type") String type) {
        return Result.success(customerOrderMapper.getSaleMoneyByStoreType(type));
    }

    /**
     * 根据店铺id获取销售额
     * @param id
     * @return
     */
    @GetMapping("/getSaleMoneyByShopId")
    public Result getSaleMoneyByShopId(@RequestParam("id") String id) {
        return Result.success(customerOrderMapper.getSaleMoneyByShopId(id));
    }

    /**
     * 根据店铺id获取销售量
     * @param id
     * @return
     */
    @GetMapping("/getSaleQuantityByShopId")
    public Result getSaleQuantityByShopId(@RequestParam("id") String id) {
        return Result.success(customerOrderMapper.getSaleQuantityByShopId(id));
    }

    /**
     * 按照客户订单状态获取订单数量
     */
    @GetMapping("/getOrderQuantityByStatus")
    public Result getOrderQuantityByStatus() {
        List<Map<String, Integer>> list = customerOrderMapper.getOrderQuantityByStatus();
        return Result.success(list);
    }
}
